# encoding: UTF-8

class DocumentsController < ApplicationController
  # GET /documents
  # GET /documents.xml
  def index
    respond_to do |format|      
      format.json {
        begin
            if params[:category]
              @category = Category.find(params[:category])
              if @category != nil && @current_account.categories.member?(@category)
                if (params[:search_query] != nil && params[:search_query] != "")
                  if !@current_account.admin
                      @documents = Document.joins("right join accounts_documents on documents.id = accounts_documents.document_id").where("accounts_documents.account_id = ? and category_id = ? and spanish_similarity(name,?) < 1",@current_account.id,params[:category],params[:search_query]).order("upload_at desc").paginate(:page => params[:page],:per_page => 6)
                  else
                      @documents = Document.where("category_id = ? and spanish_similarity(name,?) < 1",params[:category],params[:search_query]).order("upload_at desc").paginate(:page => params[:page],:per_page => 6)        
                  end
                else
                  if !@current_account.admin
                      @documents = Document.joins("right join accounts_documents on documents.id = accounts_documents.document_id").where("accounts_documents.account_id = ? and category_id = ?",@current_account.id,params[:category]).order("upload_at desc").paginate(:page => params[:page],:per_page => 6)
                  else
                      @documents = Document.where(:category_id => params[:category]).order("upload_at desc").paginate(:page => params[:page],:per_page => 6)
                  end
                end

                render :json => {
                    :category_id => @category.id,
                    :category_type => @category.category_type,
                    :category_name => @category.name,
                    :currentPage => @documents.current_page,
                    :perPage => @documents.per_page,
                    :totalEntries => @documents.total_entries,
                    :entries => @documents.as_json( :only => [:id,:name,:description,:category_id,:avatar,:created_at,:updated_at,:upload_at] , :methods => [:content_url])
                }          
              end
            end
        rescue => e
          logger.error e.backtrace.join("\n")
        end
      }
    end
  end
  
  def events
    respond_to do |format|
      format.json {
        @active_section = Section.find_by_short_name("Agendas")
        @subsections = @active_section.subsections

        @events = Array.new
        @subsections.each do |section|
            @categories_ids = section.categories.map { |cat| cat.id }
            if @current_account.admin
                @documents = Document.joins("right join accounts_categories on documents.category_id = accounts_categories.category_id ").where(:category_id => @categories_ids).where("accounts_categories.account_id = ?",@current_account.id).map do |d| 
                    { :title => d.name, :description => d.description,:start => d.upload_at , :document => d.content_url, :color => section.event_color }
                end
            else
                @documents = Document.joins("right join accounts_categories on documents.category_id = accounts_categories.category_id right join accounts_documents on documents.id = accounts_documents.document_id").where(:category_id => @categories_ids).where("accounts_categories.account_id = ? and accounts_documents.account_id = ?",@current_account.id,@current_account.id).map do |d| 
                    { :title => d.name, :description => d.description,:start => d.upload_at , :document => d.content_url, :color => section.event_color }
                end    
            end
            @events.concat(@documents)
        end
        
        render :json => @events
      }
    end
  end

  # GET /documents/1
  # GET /documents/1.xml
  def show
    @document = Document.find(params[:id])
  end

  # GET /documents/new
  # GET /documents/new.xml
  def new
    @document = Document.new
    @close = params[:close]
    @category_id = params[:category]
    @document.category_id = @category_id
    @sectionAgendaPleno = Section.where(:short_name => "Agendas de Pleno").first
    @agendaPleno = Category.where(:section_id => @sectionAgendaPleno.id).first   
    @sectionAgendaPermanente = Section.where(:short_name => "Comisión Permanente").first
    @agendaPermanente = Category.where(:section_id => @sectionAgendaPermanente.id).first
    @sesionesOrdinarias = Category.where(:category_code_name => "ordinaria")
    @sesionesExtraOrdinarias = Category.where(:category_code_name => "extraordinaria")
    render :layout => "popup"
  end

  # GET /documents/1/edit
  def edit
    @document = Document.find(params[:id])
  end

  # POST /documents
  # POST /documents.xml
  def create
    @document = Document.new(params[:document])

    respond_to do |format|
      if @document.save
        @close = true
      else
        flash[:error] = "Hubo un error al grabar el documento. Intentelo nuevamente"
        @close = false
      end
      format.html { redirect_to :action => "new", :close => @close, :category => @document.category_id }
    end
  end

  # PUT /documents/1
  # PUT /documents/1.xml
  def update
    @document = Document.find(params[:id])

    respond_to do |format|
      if @document.update_attributes(params[:document])
        format.html { redirect_to(@document, :notice => 'Document was successfully updated.') }   
      else
        format.html { render :action => "edit" }
      end
    end
  end

  # DELETE /documents/1
  # DELETE /documents/1.xml
  def destroy
    @document = Document.find(params[:document_id])
    @document.destroy
    render :json => {success:true}
  end

  def permissions
    @close = params[:close]
    @document = Document.find(params[:id])
    @accounts = Account.where(:admin => false)
    @sectionAgendaPleno = Section.where(:short_name => "Agendas de Pleno").first
    @agendaPleno = Category.where(:section_id => @sectionAgendaPleno.id).first   
    @sectionAgendaPermanente = Section.where(:short_name => "Comisión Permanente").first
    @agendaPermanente = Category.where(:section_id => @sectionAgendaPermanente.id).first
    @sesionesOrdinarias = Category.where(:category_code_name => "ordinaria")
    @sesionesExtraOrdinarias = Category.where(:category_code_name => "extraordinaria")
    render :layout => "popup"
  end

  def savepermissions
    if params[:document][:account_ids]
      params[:document][:account_ids] = params[:document][:account_ids].map{|k, v| k}
    else
      params[:document][:account_ids] = []
    end
    @document = Document.find(params[:document][:id])

    respond_to do |format|
      if @document.update_attributes(params[:document])
        @close = true
      else
        flash[:error] = "Hubo un error al grabar el documento. Intentelo nuevamente"
        @close = false
      end
      format.html { redirect_to :controller => "documents", :action => "permissions", :id => @document.id, :close => @close }
    end    
  end

end
